from django.shortcuts import render,get_object_or_404
import markdown
# Q 对象用于包装查询表达式，其作用是为了提供复杂的查询逻辑
from django.db.models import Q
from .models import Category,Tag,Post
from comments.forms import CommentForm
# 发送邮件
import smtplib
from email.mime.text import MIMEText
# 博客主页
def index(request):
    post_list = Post.objects.all().order_by('-created_time')
    '''
    order_by 方法对这个返回进行排序。排序依据是文章的创建时间
    '''
    return render(request, 'blog/index.html', context={'post_list': post_list})
# 文章主要内容页
def detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.increase_views()# 阅读量+1
    # 文章按照富文本进行渲染
    post.body = markdown.markdown(post.body,
                                  extensions=[
                                      'markdown.extensions.extra',
                                      'markdown.extensions.codehilite',
                                      'markdown.extensions.toc',
                                  ])
    # 文章评论表格
    form = CommentForm()
    # 获取全部评论
    comment_list = post.comment_set.all()
    # post.body = markdown.markdown(post.body,
	 #                                  extensions=[
	 #                                     'markdown.extensions.extra',
	 #                                     'markdown.extensions.codehilite',
	 #                                     'markdown.extensions.toc',
	 #                                  ])
    # 将文章、表单、以及文章下的评论列表传值
    context = {'post': post,
               'form': form,
               'comment_list': comment_list
               }
    return render(request, 'blog/detail.html', context=context)
# 发布时间页
def archives(request, year, month):
    post_list = Post.objects.filter(created_time__year=year,
                                    created_time__month=month
                                    ).order_by('-created_time')
    return render(request, 'blog/index.html', context={'post_list': post_list})
# 文章分类页
def category(request, pk):
    cate = get_object_or_404(Category, pk=pk)
    post_list = Post.objects.filter(category=cate).order_by('-created_time')
    return render(request, 'blog/index.html', context={'post_list': post_list})
# 联系
def contact(request):
    if request.method == 'POST':
        user = request.POST.get('user')
        # 邮件服务器
        mail_server = 'smtp.qq.com'
        # 用户名
        mail_username = '1337983798@qq.com'
        # 密码，通过环境变量获取，可以避免隐私信息的暴露
        # 或授权码，QQ邮箱需要使用授权码
        mail_password = 'fxtlwernbugpbadd'
        # 邮件内容
        content = 'QQ:1337983798' \
                  '微信：18438603979'
        # 创建用于发送的邮件消息对象
        # 参数1：邮件内容
        # 参数2：内容类型，plain表示普通文本，html表示网页
        message = MIMEText(content)
        # 设置主题
        message['Subject'] = '联系方式邮件'
        # 设置发送者
        message['From'] = mail_username

        # 创建用于发送邮件的对象
        # SMTP：邮件不加密，端口25
        # SMTP_SSL：邮件加密传输，端口465，QQ邮箱必须使用加密
        mail = smtplib.SMTP(mail_server)
        # 身份认证
        mail.login(mail_username, mail_password)
        # 发送给谁
        to = user
        # 发送邮件
        mail.sendmail(mail_username, to, message.as_string())
        # 结束
        mail.quit()
        return render(request,'blog/contact.html',{'pg':'True'})
    else:
        return render(request,'blog/contact.html')

# 搜索
def search(request):
    q = request.GET.get('q')
    error_msg = ''
    if not q:
        error_msg = "请输入关键词"
        return render(request, 'blog/index.html', {'error_msg': error_msg})
    # Q(title__icontains=q)表示标题（title）含有关键词
    post_list = Post.objects.filter(Q(title__icontains=q) | Q(body__icontains=q))
    return render(request, 'blog/index.html', {'error_msg': error_msg,
                                               'post_list': post_list})
